package org.uim.cricket.util;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringEscapeUtils;

public class HTMLStringUtils {

	private static final String HTML_TAGSTART = "<";
	private static final String HTML_TAGEND = ">";

	public static StringBuilder cleanHTMLTags(StringBuilder source) {
		return cleanHTMLTags(source, false);
	}

	public static StringBuilder cleanHTMLTags(StringBuilder source, boolean removeNewLines) {
		if (source == null) {
			return null;
		}
		
		String expr = "<[^>]+>";

        Pattern p = Pattern.compile(expr);
        Matcher m = p.matcher(source.toString());
        StringBuffer sb = new StringBuffer();

        while (m.find()) {
            m.appendReplacement(sb, "");
        }
        m.appendTail(sb);

        return new StringBuilder(sb.toString());
	}

	public static StringBuilder cleanHTMLComments(StringBuilder source) {
        String expr = "\\<![ \r\n\t]*(--([^\\-]|[\r\n]|-[^\\-])*--[ \r\n\t]*)\\>";

        Pattern p = Pattern.compile(expr);
        Matcher m = p.matcher(source.toString());
        StringBuffer sb = new StringBuffer();

        while (m.find()) {
            m.appendReplacement(sb, "");
        }
        m.appendTail(sb);

        return new StringBuilder(sb.toString());
	}
	
	public static String cleanHTMLTags(String source) {
		return cleanHTMLTags(source, false);
	}

	public static String cleanHTMLTags(String source, boolean removeNewLines) {
		return cleanHTMLTags(new StringBuilder(source), removeNewLines).toString();
	}

	public static HashMap<String, String> getHTMLAttributes(String htmlTag) {
		if (htmlTag == null) return null;
		if (htmlTag.startsWith(HTML_TAGSTART)) htmlTag = htmlTag.substring(HTML_TAGSTART.length());
		if (htmlTag.endsWith(HTML_TAGEND)) htmlTag = htmlTag.substring(0, htmlTag.length() - HTML_TAGEND.length());
		
		int pos = htmlTag.indexOf(' ');
		if (pos < 0) return null;
		htmlTag = htmlTag.substring(pos + 1).trim();
		int spos = 0;
		pos = htmlTag.indexOf('=');
		if (pos < 0) return null;
		
		HashMap<String, String> attributes = new HashMap<String, String>();
		
		while (pos > 0) {
			String key = htmlTag.substring(spos, pos).trim();
			pos = htmlTag.indexOf('\"', pos + 1);
			if (pos < 0) break;
			
			spos = pos;
			pos = htmlTag.indexOf('\"', pos + 1);
			if (pos < spos) break;
			String value = htmlTag.substring(spos + 1, pos);
			value = StringEscapeUtils.unescapeHtml4(value);
			attributes.put(key, value);
			
			spos = pos + 1;
			pos = htmlTag.indexOf('=', pos + 1);
		}
		
		return attributes;
	}

	
}
